#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2018年10月22日

@author: lin
'''

import paramiko

__all__ = ['connect','close','cmd','download','upload']

class SSHConnection(object):
    def __init__(self, host=None, port=22, username='root',pwd=None):
        self.host = host
        self.port = port
        self.username = username
        self.pwd = pwd
        self.__k = None
    
    def connect(self):
        transport = paramiko.Transport((self.host,self.port))
        transport.connect(username=self.username,password=self.pwd)
        self.__transport = transport
    
    def close(self):
        self.__transport.close()
        
    def cmd(self,command):
        ssh = paramiko.SSHClient()
        ssh._transport = self.__transport
        # 执行命令
        stdin, stdout, stderr = ssh.exec_command(command)
        # 获取命令结果
        sin,sout,serr = stdin,stdout.read().decode('utf8'),stderr.read().decode('utf8')
        return sin,sout,serr
    
    def download(self,remote_path,local_path):
        sftp = paramiko.SFTPClient.from_transport(self.__transport)
        sftp.get(remote_path,local_path)
        
    def upload(self,local_path,target_path):
        # 连接，上传
        sftp = paramiko.SFTPClient.from_transport(self.__transport)
        # 将location.py 上传至服务器 /tmp/test.py
        sftp.put(local_path, target_path) 
        


